package com.xcjh.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xcjh.domain.DataAcquisition;
import com.xcjh.dto.BaseMember;
import com.xcjh.dto.yidui.YiduiMember;
import com.xcjh.eums.AppType;
import com.xcjh.service.DataAcquisitionService;
import com.xcjh.service.YiduiService;
import com.xcjh.utils.SystemUtil;
import com.xcjh.websocket.WebSocketSever;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class YiduiServiceImpl implements YiduiService {
    @Autowired
    private DataAcquisitionService dataAcquisitionService;

    @Override
    public void save(String body) {
        YiduiMember member = JSONUtil.toBean(body, YiduiMember.class);


        BaseMember msg = new BaseMember();
        msg.setAvatar_url(member.getAvatar_url());
        if (findOrSave(member) == null) {
            msg.setViewStr(getViewStr(member));
        } else {
            msg.setViewStr("@@@@@@已经有了@@@@@@@");
        }

        WebSocketSever.sendMessageByUser("yidui", JSONUtil.toJsonStr(msg));
        if(!msg.getViewStr().contains("@@@")){
            SystemUtil.writeC(msg.getViewStr());
        }
        System.out.println("收到请求,并发送");
    }

    private DataAcquisition findOrSave(YiduiMember push) {
        //所有数据,不管发没发送过
        List<DataAcquisition> dbAll = dataAcquisitionService.lambdaQuery()
                .eq(DataAcquisition::getAppId, push.getMember_id())
                .eq(DataAcquisition::getType, AppType.YIDUI.getMessage())
                .list();
        if (CollectionUtil.isNotEmpty(dbAll)) {
            return dbAll.get(0);
        }
        DataAcquisition d = new DataAcquisition();
        d.setAppId(push.getMember_id());
        d.setSend(true);
        d.setType(AppType.YIDUI.getMessage());
        d.setDemoJson(JSONUtil.toJsonStr(push));
        String relyPhone = StrUtil.isNotEmpty(push.getPhone()) && !push.getPhone().contains("*") ? push.getPhone() : null;
        d.setOther(StrUtil.isNotEmpty(push.getWechat()) ? push.getWechat() : relyPhone);
        dataAcquisitionService.save(d);
        return null;
    }


    String body = "{\"is_risk\":false,\"is_blocked\":false,\"is_canceled\":false,\"status\":0,\"platform\":1,\"age\":22,\"avatar_status\":0,\"avatar_url\":\"https://img.520yidui.com/uploads/member_avatar/avatar/124093865/4a4d3f942a265deb34db64923dee01eb.jpg@!normal\",\"temp_avatar_url\":\"\",\"birthday\":\"2001-05-01\",\"constellation\":\"金牛座\",\"blind_date_duration\":126,\"blind_date_record\":[],\"current_location\":{\"province\":\"四川\",\"city\":\"成都\"},\"ab_position\":{},\"grade\":\"rank_d\",\"height\":160,\"id\":\"68c32f59a13731394a42e0d35fa05a00\",\"is_audio_cupid\":false,\"is_break_transgress\":false,\"is_matchmaker\":false,\"is_small_team_cupid\":false,\"is_takeoff_the_single_master\":false,\"is_transgress_black\":false,\"is_trump\":false,\"is_vip\":false,\"location\":\"四川\",\"logout\":false,\"block\":false,\"member_gift_list\":[],\"member_id\":124093865,\"monologue\":\"主动就会有故事\",\"monologue_example\":\"96年巨蟹女，长相身材自认还可以。有一只猫，喜欢追剧看综艺，琴棋书画都会一些。身高控，偏好180+的运动型长腿欧巴，希望你年龄比我大，可以稳重话不多，我会给你撒娇给你小浪漫，也会给你甜甜的恋爱。\",\"monologue_status\":0,\"nickname\":\"L\",\"partnership_count\":0,\"online\":6,\"photo_auth\":false,\"rose_count\":0,\"sex\":1,\"video_auth\":{\"status\":\"avaliable\",\"video_url\":\"\"},\"video_auth_success\":true,\"vip\":false,\"decorate\":\"\",\"photos\":null,\"photos_v2\":null,\"is_checking\":false,\"members_tags\":[],\"relation\":false,\"is_free_chat\":true,\"member_relation\":{\"is_black\":false,\"is_blacked\":false,\"is_friend\":false,\"is_like\":false,\"is_liked\":false,\"is_request\":false,\"is_requested\":false},\"live_status\":{\"desc\":\"视频房间相亲\",\"is_live\":false,\"scene_id\":3226,\"scene_type\":\"VideoRoom\",\"simple_desc\":\"相亲中\",\"status\":\"stop\"},\"detail\":{\"blood_type\":\"\",\"education\":\"大专\",\"is_livewithparent\":\"\",\"is_drink\":\"\",\"is_need_baby\":\"\",\"is_smoking\":\"\",\"is_twoplacelove\":\"\",\"living_condition\":\"\",\"marriage\":\"\",\"profession\":\"\",\"salary\":\"\",\"university\":\"\",\"profession_id\":0,\"house_city\":\"\",\"company\":\"\"},\"relationship_proposal\":{\"age\":\"\",\"content\":\"\",\"education\":\"\",\"height\":\"\",\"location\":\"\",\"salary\":\"\",\"start_age\":0,\"end_age\":0,\"location_id\":0,\"education_id\":0,\"start_height\":0,\"end_height\":0,\"salary_id\":0,\"city\":\"\",\"city_id\":0},\"tag_list\":[],\"labels\":[],\"check_userinfo\":0,\"consume_rose_count\":0,\"cards\":null,\"money\":0,\"invited\":false,\"vip_remain\":0,\"sweetheart_brand\":null,\"invited_member_blind_date_duration_reward_desc\":\"\",\"permission\":null,\"wechat\":\"l13659005375\",\"wealth\":\"\",\"invite_code\":\"\",\"vip_toast_config\":0,\"info_score\":0,\"is_white_cupid\":false,\"is_exclusive_cupid\":false,\"rich_r\":false,\"hello\":null,\"register_experience_card_num\":0,\"first_paid_at\":0,\"register_at\":1633178400,\"register_api_key\":\"7e08df24\",\"channel_name\":\"market_VIVO\",\"phone_validate\":true,\"phone\":\"184******94\",\"hometown\":\"\",\"gifts\":null,\"small_teams\":[],\"moment\":{\"content\":\"\",\"count\":2,\"image\":null},\"single_count\":0,\"creator_label\":{\"is_excellent_creator\":false,\"label_type\":0,\"label_text\":\"\"},\"wealth_value\":\"\",\"forbidden_request_friend\":false,\"live_video_auth\":{\"status\":\"refused\",\"live_video_pic_url\":\"https://img.520yidui.com/uploads/member_avatar/avatar/124093865/4a4d3f942a265deb34db64923dee01eb.jpg@!normal\",\"live_video_url\":\"\"},\"zhima_auth\":\"\",\"receive_gift_list\":null,\"flag\":false,\"weixin_mini\":{\"is_exchanged\":0,\"is_guide_show\":true,\"is_improve_information\":false,\"is_matchmaker\":false,\"leave_message\":\"\",\"matchmaker_work_name\":\"\",\"target_wechat\":\"\",\"wx_avatar\":\"\",\"wx_name\":\"\",\"zhima_auth_target\":\"\"},\"badge\":null,\"brand\":{\"avatar\":\"\",\"decorate\":\"\",\"guardian_angel\":false,\"member_id\":\"\",\"name\":\"\",\"nickname\":\"\",\"source\":\"\",\"svga_name\":\"\"},\"city_id\":373,\"special_right_user_flag\":false,\"video_match_maker\":false,\"blind_date\":{\"authentication_birthday\":\"\",\"is_happy_take\":false},\"member_privilege\":null,\"extend_brand\":null,\"gravity\":{\"gravity\":0,\"level\":-1,\"show_gravity\":false,\"max_level\":0,\"gravity_info\":null},\"ip_province\":\"四川\",\"talent_show\":false,\"guest\":false,\"union\":false,\"strict_info\":{\"strict_status\":0,\"remark\":\"\",\"cupid_id\":\"cbc22a7313f2ffd79ff0a6a5b2b79e79\",\"recommend_pics_url\":null,\"recommend_pics_text\":null,\"pics_radio\":null}}";

    private String getViewStr(YiduiMember member) {
//        YiduiMember member = JSONUtil.toBean(y.body, YiduiMember.class);
        String birthdayStr = toViewDate(member);
        String birthdayView = StrUtil.isEmpty(birthdayStr) ? "" : "她说你是" + birthdayStr + "的,我觉得年龄合适.";
        String phoneView = StrUtil.isNotEmpty(member.getPhone()) ? " 她刚刚联系你" + member.getPhone() + " 打了几个都没有打通呢?赶紧上线回个消息,她等着我们连线呢." : "";
        String wechatView = StrUtil.isNotEmpty(member.getWechat()) ? " 和你连不上线,她让我加你" + member.getWechat() + "自己和你聊." : "";
//        String my="我在成都工作,职位是架构师.";
//        return "亲,我是红娘牵线介绍的. "+my+birthdayView+phoneView+wechatView;
        String my = "我在成都工作,职位是架构师.";
        return "亲,我刚刚找红娘准备和你牵线,红娘介绍认识的. " + my + birthdayView + phoneView + wechatView;
    }

    public static String toViewDate(YiduiMember member) {
        String birthday = member.getBlind_date() != null && StrUtil.isNotEmpty(member.getBlind_date().getAuthentication_birthday()) ?
                member.getBlind_date().getAuthentication_birthday() : member.getBirthday();
        return toViewDate(birthday);
    }


    public static String toViewDate(String birthday) {
        if (StrUtil.isEmpty(birthday)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfView = new SimpleDateFormat("yy年MM月dd");
        try {
            Date date = sdf.parse(birthday);
            return sdfView.format(date);
        } catch (ParseException e) {
            System.out.println("解析:" + birthday);
            throw new RuntimeException(e);
        }
    }

}
